﻿using System.DirectoryServices.Protocols;
using System.Net;

namespace BlazorAdmin.Extensions
{
    /// <summary>
    /// 域验证帮助类
    /// </summary>
    public class LdapHelper
    {
        /// <summary>
        /// 域登录
        /// </summary>
        /// <param name="loginName">域账号</param>
        /// <param name="password">域密码</param>
        /// <param name="server"></param>
        /// <returns></returns>
        public static bool Login(string loginName, string password, params string[] servers)
        {
            try
            {
                string? server = null != servers && servers.Length > 0 ? servers[0] : null;
                LdapDirectoryIdentifier identifier = new(server: server, true, false);
                NetworkCredential networkCredential = new(loginName, password);
                using LdapConnection ldap = new(server);
                ldap.Bind(networkCredential);
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
        }
    }
}